import React from 'react';
import { Route, Switch, withRouter, Redirect } from 'react-router-dom';
//withRouter用于向下传递props
import { observer, inject } from 'mobx-react';

@inject('userStore') //调用判断用户是否登录的方法
@observer
class PrivateRoute extends React.Component {
  constructor(props) {
    super(props);
  }
  routerFun = list => {
    return list.map(route => {
      if (route.meta && route.meta.require) {
        //第一步，验证是否需要登录就可进入
        if (this.props.userStore.user.isLogin) {
          //判断是否登录
          // const permissions = this.props.userStore.user.premission; //获取登录用户的权限
          if (route.children) {
            //路由是否存在子路由
            return (
              <Route
                key={route.name}
                path={route.path}
                render={() => (
                  <route.component key={route.name} {...this.props}>
                    {this.routerFun(route.children)}
                    <Route
                      key={route.name}
                      exact
                      path={route.path}
                      render={() => <Redirect to={route.redirect} />}
                    />
                  </route.component>
                )}
              />
            );
          } else {
            //渲染路由
            return <Route key={route.name} exact path={route.path} component={route.component} />;
          }
        } else {
          //没有登录
          return <Redirect key={route.name} to="/Login" />;
        }
      } else if (route.redirect) {
        //第二步，判断该路由是否需要重定向
        return (
          <Route
            key={route.name}
            exact
            path={route.path}
            render={() => <Redirect to={route.redirect} />}
          />
        );
      } else {
        //不需要登录
        return <Route key={route.name} path={route.path} exact component={route.component} />;
      }
    });
  };
  render() {
    let { routerList } = this.props;
    return <Switch>{this.routerFun(routerList)}</Switch>;
  }
}

export default withRouter(PrivateRoute);
